'use strict';
exports.main = async (event, context) => {
	//event为客户端上传的参数

	if (event.JSCODE && event.provider) {
		
		//登录时获取的 code
		let JSCODE = event.JSCODE

		//小程序 appId
		let APPID
		
		//小程序 appSecret
		let SECRET
		
		let apiUrl = ""
		if (event.provider == "weixin") {
			 apiUrl += "https://api.weixin.qq.com"
			 APPID = "wx225f33b3a7ba56c1"
			 SECRET = "9b793add543735e527e72f26644215d9"
		}else if(event.provider == "qq"){
			 apiUrl += "https://api.q.qq.com"
			 //有件必达
			 APPID = "1112175074"
			 SECRET = "UUxDttxE3ffzIxAq"
			 
		}
		apiUrl+="/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET +
				"&js_code=" + JSCODE + "&grant_type=authorization_code"

		const res = await uniCloud.httpclient.request(apiUrl, {
			method: 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded' // 默认值
			},
			contentType: 'json', // 指定以application/json发送data内的数据
			dataType: 'json' // 指定返回值为json格式，自动进行parse
		})

		console.log(res)
		return {
			code: 200,
			msg: "获取成功！",
			data: res
		}

	} else {
		//返回数据给客户端
		return {
			code: 501,
			msg: "获取失败，JSCODE为空!",
			data: event
		}
	}
};
